const FtpSvr = require('ftp-srv');
const path = require('path');
const address = require('address');
const fs = require('fs');
const HOST = process.env.FTP_HOST || address.ip() || "127.0.0.1";
const PORT = process.env.FTP_PORT || "21";
const ROOT = path.join(process.cwd(), process.env.RELATIVE_PATH)
			 || path.join(process.cwd(), 'upload');
const ftpServer = new FtpSvr(`ftp://${HOST}:${PORT}`, {});

ftpServer.on('login', (data, resolve, reject) => {
	if (data.username==='1' && data.password==='1') {

		resolve({
			root: ROOT,
			cwd: '/'
		});

	} else {
		reject('no');
	}

	data.connection.on('RETR',(error,filePath) => {
		if(!error){
			console.log(`${filePath} is downloaded !`);
		}else{
			console.log(`downloaded failed! ${error}`);
		}
	});

	data.connection.on('STOR', (error, fileName) => {
		if(!error){
			console.log(`${fileName} is uploaded !`);
		}else{
			console.log(`${fileName} uploaded failed! ${error}`);
		}
	});

	data.connection.on('RNFR', (error, fileName) => {
		if(!error){
			console.log(`${fileName} is RNFR !`);
		}else{
			console.log(`${fileName} RNFR failed! ${error}`);
		}
	});

});

ftpServer.on('client-error',(data) => {

});


ftpServer.listen().then(() => {
	console.log('ftp server listening at', HOST + ':' + PORT);
});
